package com.corner.model.leancloud.helper;

import android.content.Intent;
import android.text.TextUtils;

import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMClientEventHandler;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMConversationEventHandler;
import com.avos.avoscloud.im.v2.AVIMTypedMessage;
import com.avos.avoscloud.im.v2.AVIMTypedMessageHandler;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;
import com.corner.R;
import com.corner.app.App;
import com.corner.app.ConsTants;
import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.UserHelper;

import com.corner.model.db.Conversation;
import com.corner.model.db.ConversationDao;
import com.corner.model.db.DBConstans;
import com.corner.model.db.Session;
import com.corner.ui.activity.ChatActivity;
import com.corner.utils.CommonUtil;
import com.corner.utils.LogUtil;
import com.corner.utils.NotificationUtil;
import com.corner.utils.ToastUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

/**
 * Created by Administrator on 2015/5/12.
 */
public class ChatEventHanlder {
    public static boolean isConnected = true;

    // 处理网络状态变化事件
    public static class CustomNetworkHandler extends AVIMClientEventHandler {
        @Override
        public void onConnectionPaused(AVIMClient client) {
            // 请按自己需求改写
            isConnected = false;
            LogUtil.e("connect paused");
//            if (App.application.sessionDaoImp != null) {
//                App.application.sessionDaoImp.updateToSentFailed();
//            }
            ToastUtil.showCustomToastInRelease(App.application, App.application.getString(R.string.im_connection_pause));
        }

        @Override
        public void onConnectionResume(AVIMClient client) {
            // 请按自己需求改写
            isConnected = true;
            LogUtil.e("connect resume");
//            if (App.application.sessionDaoImp != null) {
//                App.application.sessionDaoImp.updateToSentFailed();
//            }
            ToastUtil.showCustomToastInRelease(App.application, App.application.getString(R.string.im_connection_resume));
        }
    }

    // 处理对话成员变化事件
    public static class CustomConversationHandler extends AVIMConversationEventHandler {

        @Override
        public void onMemberLeft(AVIMClient client, AVIMConversation conversation, List<String> members, String kickedBy) {
        }

        @Override
        public void onMemberJoined(AVIMClient client, AVIMConversation conversation, List<String> members, String invitedBy) {
        }

        @Override
        public void onKicked(AVIMClient client, AVIMConversation conversation, String kickedBy) {
        }

        @Override
        public void onInvited(AVIMClient client, AVIMConversation conversation, String operator) {
        }
    }


    public static class MsgHandler extends AVIMTypedMessageHandler<AVIMTypedMessage> {

        /**
         * 插入会话
         *
         * @param avimConversation
         */
        private static void insertConversationIntoDB(AVIMConversation avimConversation) {
            com.corner.model.db.Conversation dbConversation = App.application.daoSession.getConversationDao()
                    .queryBuilder().where(ConversationDao.Properties.ConversationId.eq(avimConversation.getConversationId()))
                    .unique();
            if (dbConversation == null) {
                dbConversation = new Conversation();
                dbConversation.setConversationId(avimConversation.getConversationId());
                dbConversation.setMainUser(avimConversation.getCreator());
                dbConversation.setCustomUser(searchDestinationOfMessage(avimConversation,
                        dbConversation.getMainUser()));
                dbConversation.setMainIsInBlackList(false);
                dbConversation.setCustomIsInBlackList(false);
                App.application.daoSession.getConversationDao().insertOrReplace(dbConversation);
            }
        }

        /**
         * 获取该会话中信息的目的地（接受者）
         *
         * @param conversation      会话
         * @param sourceIdOfMessage 信息的来源
         * @return 接受者的id
         */
        private static String searchDestinationOfMessage(AVIMConversation conversation, String sourceIdOfMessage) {
            for (String member : conversation.getMembers()) {
                if (!member.equals(sourceIdOfMessage)) {
                    return member;
                }
            }
            return null;
        }

        @Override
        public void onMessage(AVIMTypedMessage message, AVIMConversation conversation, AVIMClient client) {
            // 请按自己需求改写
            if (App.application.daoSession==null){
                App.application.initSession();
            }
            switch (message.getMessageType()) {
                case -1:
                    AVIMTextMessage textMsg = (AVIMTextMessage) message;
                    Map<String, Object> pamas = textMsg.getAttrs();
                    Session  session = new Session();
                    session.setSessionId(pamas.get(DBConstans.SESSION_ID).toString());
                    session.setMessageId(textMsg.getMessageId());
                    session.setIsSent(DBConstans.SENT);
                    session.setType(pamas.get(DBConstans.TYPE).toString());
                    session.setTimestamp(new Date(textMsg.getTimestamp()));
                    setFromAndTo(conversation, session, textMsg);

                    session.setIsReaded(false);
                    session.setText(textMsg.getText());
                    switch (session.getType()){
                        case DBConstans.COMMENT:
                            session.setInfoId(Long.valueOf(pamas.get(DBConstans.INFOID).toString()));
                            break;
                        case DBConstans.SHARE:
                            session.setLocationId(Long.valueOf(pamas.get(DBConstans.LOCATION_ID).toString()));
                            break;
                        case DBConstans.PIC_AUDIO:
                            session.setPic(pamas.get(DBConstans.PIC).toString());
                            session.setAudio(pamas.get(DBConstans.AUDIO).toString());
                            session.setAudioDuration(pamas.get(DBConstans.AUDIODURATION).toString());
                            break;
                        case DBConstans.PIC:
                            session.setPic(pamas.get(DBConstans.PIC).toString());
                            break;
                        case DBConstans.AUDIO:
                            session.setAudio(pamas.get(DBConstans.AUDIO).toString());
                            session.setAudioDuration(pamas.get(DBConstans.AUDIODURATION).toString());
                            break;
                        case DBConstans.BLACK_LIST:
                            session = null;
                            addToBlackList(conversation);
                            return;
                    }
                    App.application.daoSession.getSessionDao().insertOrReplace(session);
                    showNotify(session);
                    break;
            }
        }

        /**
         * 将自己加入到该会话的黑名单中
         *
         * @param avimConversation
         */
        private void addToBlackList(AVIMConversation avimConversation) {
            com.corner.model.db.Conversation dbConversation = App.application.daoSession.getConversationDao()
                    .queryBuilder().where(ConversationDao.Properties.ConversationId.eq(avimConversation.getConversationId()))
                    .unique();
            if (dbConversation==null) {
                dbConversation = new Conversation();
                dbConversation.setConversationId(avimConversation.getConversationId());
                dbConversation.setMainUser(avimConversation.getCreator());
                dbConversation.setCustomUser(searchDestinationOfMessage(avimConversation,
                        dbConversation.getMainUser()));
            }
            if (dbConversation.getMainUser().equals(User.getCurrentUser().getObjectId().toString())) {
                dbConversation.setMainIsInBlackList(true);
            } else {
                dbConversation.setCustomIsInBlackList(true);
            }
            App.application.daoSession.getConversationDao().insertOrReplace(dbConversation);
        }

        /**
         * 设置from和to的userId
         *
         * @param conversation
         * @param session
         * @param avimTypedMessage
         */
        private void setFromAndTo(AVIMConversation conversation, Session session, AVIMTypedMessage avimTypedMessage) {
            session.setFromUserId(avimTypedMessage.getFrom());
            session.setToUserId(searchDestinationOfMessage(conversation, session.getFromUserId()));
            if (session.getFromUserId().equals(User.getCurrentUser().getObjectId().toString())) {
                session.setSessionName( session.getToUserId());
            } else {
                session.setSessionName( session.getFromUserId());
            }
            insertConversationIntoDB(conversation);
        }

        /**
         * 显示通知
         *
         * @param session
         */
        private void showNotify(final Session session) {

            com.corner.model.db.User user = App.application.daoSession.getUserDao().load(Long.valueOf(session.getFromUserId()));
            if (user == null) {
                UserHelper.getUser(Long.valueOf(session.getFromUserId())).subscribe(new Action1<User>() {
                    @Override
                    public void call(User user) {
                        if (user != null) {
                            UserHelper.saveUserToDb(user);
                            MsgHandler.this.notify(user.getUsername(), session);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
            } else {
                MsgHandler.this.notify(user.getUsername(), session);
                UserHelper.saveUser(Long.valueOf(session.getFromUserId()));
            }
        }

        /**
         * @param name     用户名字
         * @param session
         */
        private void notify(String name, Session session) {
            if (!User.getCurrentUser().getObjectId().toString().equals(session.getFromUserId())
                    && !(ChatActivity.class.getName().equals(CommonUtil.getTopActivityClassName(App.application))
                    && session.getFromUserId().equals(ChatActivity.userId))) {
                String content = "";
                switch (session.getType()) {
                    case DBConstans.TEXT:
                        content = session.getText();
                        break;
                    case DBConstans.COMMENT:
                        content = App.application.getString(R.string.session_comment_notice) + session.getText();
                        break;
                    case DBConstans.AUDIO:
                        content = App.application.getString(R.string.session_audio_notice);
                        break;
                    case DBConstans.PIC:
                        content = App.application.getString(R.string.session_pic_notice);
                        break;
                    case DBConstans.PIC_AUDIO:
                        content = App.application.getString(R.string.session_pic_audio_notice);
                        break;
                }
                Intent intent = new Intent(App.application, ChatActivity.class);
                intent.putExtra(ChatActivity.INTENT_ID, ChatActivity.CHAT);
                intent.putExtra(ChatActivity.USER_ID_IN_LONG, Long.valueOf(session.getFromUserId()));
                String title = "";
                if (TextUtils.isEmpty(name)) {
                    title = App.application.getString(R.string.on_message_notify_title);
                } else {
                    title = App.application.getString(R.string.on_message_notify_pre) + name + App.application.getString(R.string.on_message_notify_back);
                }
                NotificationUtil.showNotificationWithActivityIntent(App.application, R.drawable.ic_launcher, title, content, intent, ConsTants.MESSAGE_NOTIFY);
            }
        }

        @Override
        public void onMessageReceipt(AVIMTypedMessage message, AVIMConversation conversation, AVIMClient client) {
            // 请加入你自己需要的逻辑...
        }
    }

}
